// 播放列表管理云对象
const UniID = require('uni-id-common')
module.exports = {
	_before: function () {
		// 通用预处理器
		this.startTime = Date.now();
	},

	/**
	 * 获取设备播放列表
	 * @param {string} deviceId 设备ID
	 * @returns {object} 播放列表
	 */
	async getPlaylists({deviceId}) {
		
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		let userId = uid
		if (!deviceId || !userId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			const dbCmd = db.command;
			
			// 检查设备权限
			const deviceResult = await db.collection('sh_user_device').where(
				dbCmd.and([
					{_id: deviceId},
					dbCmd.or([
						{owner_id: userId},
						{shared_users: dbCmd.in([userId])}
					])
				])
			).get();

			if (deviceResult.data.length === 0) {
				return {
					errCode: 'NO_PERMISSION',
					errMsg: '无权限访问此设备'
				}
			}

			// 获取播放列表
			const playlistResult = await db.collection('sh_user_playlist').where({
				device_id: deviceId
			}).get();

			if (playlistResult.data.length === 0) {
				// 创建默认播放列表
				const newPlaylist = await db.collection('sh_user_playlist').add({
					device_id: deviceId,
					patterns: [],
					current_index: 0,
					play_mode: 0,
					auto_play: true,
					create_time: new Date(),
					update_time: new Date()
				});

				return {
					errCode: 0,
					errMsg: '获取成功',
					data: {
						_id: newPlaylist.id,
						device_id: deviceId,
						patterns: [],
						current_index: 0,
						play_mode: 0,
						auto_play: true
					}
				}
			}

			const playlist = playlistResult.data[0];
			
			// 获取设备当前状态，确定正在播放的图案
			const deviceDetail = await db.collection('sh_user_device').doc(deviceId).get();
			const device = deviceDetail.data[0];
			const currentPlayingId = device && device.current_pattern ? device.current_pattern.pattern_id : '';
			
			// 获取图案详细信息
			if (playlist.patterns.length > 0) {
				const patternIds = playlist.patterns.map(p => p.pattern_id);
				const patternResult = await db.collection('sh_pattern').where({
					_id: dbCmd.in(patternIds)
				}).get();

				// 合并图案信息，并标记当前播放状态
				playlist.patterns = playlist.patterns.map(p => {
					const pattern = patternResult.data.find(pt => pt._id === p.pattern_id);
					return {
						...p,
						pattern: pattern || null,
						is_playing: p.pattern_id === currentPlayingId
					};
				}).filter(p => p.pattern !== null);
			}

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: playlist
			}
		} catch (error) {
			console.error('获取播放列表失败:', error);
			return {
				errCode: 'GET_PLAYLIST_FAILED',
				errMsg: '获取播放列表失败'
			}
		}
	},

	/**
	 * 添加图案到播放列表
	 * @param {string} deviceId 设备ID
	 * @param {string} patternId 图案ID
	 * @param {number} position 插入位置（可选）
	 * @returns {object} 添加结果
	 */
	async addPattern({deviceId, patternId, position}) {
		
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		let userId = uid
		
		if (!deviceId || !userId || !patternId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			const dbCmd = db.command;
			
			// 检查设备权限
			const deviceResult = await db.collection('sh_user_device').where(
				dbCmd.and([
					{_id: deviceId},
					dbCmd.or([
						{owner_id: userId},
						{shared_users: dbCmd.in([userId])}
					])
				])
			).get();

			if (deviceResult.data.length === 0) {
				return {
					errCode: 'NO_PERMISSION',
					errMsg: '无权限操作此设备'
				}
			}

			// 检查图案是否存在
			const patternResult = await db.collection('sh_pattern').doc(patternId).get();
			if (patternResult.data.length === 0) {
				return {
					errCode: 'PATTERN_NOT_FOUND',
					errMsg: '图案不存在'
				}
			}

			// 获取播放列表
			const playlistResult = await db.collection('sh_user_playlist').where({
				device_id: deviceId
			}).get();

			let playlist;
			if (playlistResult.data.length === 0) {
				// 创建播放列表
				const newPlaylist = await db.collection('sh_user_playlist').add({
					device_id: deviceId,
					patterns: [],
					current_index: 0,
					play_mode: 0,
					auto_play: true,
					create_time: new Date(),
					update_time: new Date()
				});
				playlist = {
					_id: newPlaylist.id,
					patterns: []
				};
			} else {
				playlist = playlistResult.data[0];
			}

			// 检查图案是否已在列表中
			const existPattern = playlist.patterns.find(p => p.pattern_id === patternId);
			if (existPattern) {
				return {
					errCode: 'PATTERN_EXISTS',
					errMsg: '图案已在播放列表中'
				}
			}

			// 添加图案到列表
			const newPattern = {
				pattern_id: patternId,
				sort_order: position !== undefined ? position : playlist.patterns.length,
				add_time: new Date()
			};

			let newPatterns;
			if (position !== undefined && position < playlist.patterns.length) {
				// 在指定位置插入
				newPatterns = [...playlist.patterns];
				newPatterns.splice(position, 0, newPattern);
				// 更新后续图案的排序
				for (let i = position + 1; i < newPatterns.length; i++) {
					newPatterns[i].sort_order = i;
				}
			} else {
				// 添加到末尾
				newPatterns = [...playlist.patterns, newPattern];
			}

			// 更新播放列表
			await db.collection('sh_user_playlist').doc(playlist._id).update({
				patterns: newPatterns,
				update_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '添加成功'
			}
		} catch (error) {
			console.error('添加图案到播放列表失败:', error);
			return {
				errCode: 'ADD_PATTERN_FAILED',
				errMsg: '添加图案到播放列表失败'
			}
		}
	},

	/**
	 * 从播放列表删除图案
	 * @param {string} deviceId 设备ID
	 * @param {string} userId 用户ID
	 * @param {string} patternId 图案ID
	 * @returns {object} 删除结果
	 */
	async removePattern({deviceId, patternId}) {

		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		let userId = uid

		if (!deviceId || !userId || !patternId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			const dbCmd = db.command;
			
			// 检查设备权限
			const deviceResult = await db.collection('sh_user_device').where(
				dbCmd.and([
					{_id: deviceId},
					dbCmd.or([
						{owner_id: userId},
						{shared_users: dbCmd.in([userId])}
					])
				])
			).get();

			if (deviceResult.data.length === 0) {
				return {
					errCode: 'NO_PERMISSION',
					errMsg: '无权限操作此设备'
				}
			}

			// 获取播放列表
			const playlistResult = await db.collection('sh_user_playlist').where({
				device_id: deviceId
			}).get();

			if (playlistResult.data.length === 0) {
				return {
					errCode: 'PLAYLIST_NOT_FOUND',
					errMsg: '播放列表不存在'
				}
			}

			const playlist = playlistResult.data[0];
			
			// 查找并删除图案
			const patternIndex = playlist.patterns.findIndex(p => p.pattern_id === patternId);
			if (patternIndex === -1) {
				return {
					errCode: 'PATTERN_NOT_FOUND',
					errMsg: '图案不在播放列表中'
				}
			}

			const newPatterns = playlist.patterns.filter(p => p.pattern_id !== patternId);
			
			// 重新排序
			newPatterns.forEach((pattern, index) => {
				pattern.sort_order = index;
			});

			// 调整当前播放位置
			let newCurrentIndex = playlist.current_index;
			if (patternIndex < playlist.current_index) {
				newCurrentIndex = playlist.current_index - 1;
			} else if (patternIndex === playlist.current_index) {
				newCurrentIndex = Math.min(playlist.current_index, newPatterns.length - 1);
			}

			// 更新播放列表
			await db.collection('sh_user_playlist').doc(playlist._id).update({
				patterns: newPatterns,
				current_index: Math.max(0, newCurrentIndex),
				update_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '删除成功'
			}
		} catch (error) {
			console.error('删除播放列表图案失败:', error);
			return {
				errCode: 'REMOVE_PATTERN_FAILED',
				errMsg: '删除播放列表图案失败'
			}
		}
	},

	/**
	 * 调整播放列表中图案的顺序
	 * @param {string} deviceId 设备ID
	 * @param {array} patterns 新的图案顺序
	 * @returns {object} 调整结果
	 */
	async reorderPatterns({deviceId, patterns}) {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		
		if (!deviceId || !Array.isArray(patterns)) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空或格式错误'
			}
		}

		try {
			const db = uniCloud.database();
			const dbCmd = db.command;
			
			// 检查设备权限
			const deviceResult = await db.collection('sh_user_device').where(
				dbCmd.and([
					{_id: deviceId},
					dbCmd.or([
						{owner_id: userId},
						{shared_users: dbCmd.in([userId])}
					])
				])
			).get();

			if (deviceResult.data.length === 0) {
				return {
					errCode: 'NO_PERMISSION',
					errMsg: '无权限操作此设备'
				}
			}

			// 获取播放列表
			const playlistResult = await db.collection('sh_user_playlist').where({
				device_id: deviceId
			}).get();

			if (playlistResult.data.length === 0) {
				return {
					errCode: 'PLAYLIST_NOT_FOUND',
					errMsg: '播放列表不存在'
				}
			}

			const playlist = playlistResult.data[0];
			
			// 更新排序
			const newPatterns = patterns.map((pattern, index) => ({
				...pattern,
				sort_order: index
			}));

			// 更新播放列表
			await db.collection('sh_user_playlist').doc(playlist._id).update({
				patterns: newPatterns,
				update_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '调整顺序成功'
			}
		} catch (error) {
			console.error('调整播放列表顺序失败:', error);
			return {
				errCode: 'REORDER_PATTERNS_FAILED',
				errMsg: '调整播放列表顺序失败'
			}
		}
	},

	/**
	 * 批量更新播放列表图案
	 * @param {string} playlistId 播放列表ID
	 * @param {array} patternIds 图案ID数组
	 * @param {string} position 插入位置，可以是具体数字或"append"
	 * @returns {object} 更新结果
	 */
	async updatePlaylistPatterns({playlistId, patternIds, position = 'append'}) {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		
		if (!playlistId || !Array.isArray(patternIds) || patternIds.length === 0) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空或格式错误'
			}
		}

		try {
			const db = uniCloud.database();
			const dbCmd = db.command;
			
			// 获取播放列表信息
			const playlistResult = await db.collection('sh_user_playlist').doc(playlistId).get();
			
			if (playlistResult.data.length === 0) {
				return {
					errCode: 'PLAYLIST_NOT_FOUND',
					errMsg: '播放列表不存在'
				}
			}
			
			const playlist = playlistResult.data[0];
			const deviceId = playlist.device_id;
			
			// 检查设备权限
			const deviceResult = await db.collection('sh_user_device').where(
				dbCmd.and([
					{_id: deviceId},
					dbCmd.or([
						{owner_id: userId},
						{shared_users: dbCmd.in([userId])}
					])
				])
			).get();

			if (deviceResult.data.length === 0) {
				return {
					errCode: 'NO_PERMISSION',
					errMsg: '无权限操作此设备'
				}
			}
			
			// 检查图案是否都存在
			const patternResult = await db.collection('sh_pattern').where({
				_id: dbCmd.in(patternIds)
			}).get();
			
			if (patternResult.data.length !== patternIds.length) {
				return {
					errCode: 'PATTERN_NOT_FOUND',
					errMsg: '部分图案不存在'
				}
			}
			
			// 过滤掉已经在播放列表中的图案
			const existingPatternIds = playlist.patterns.map(p => p.pattern_id);
			const newPatternIds = patternIds.filter(id => !existingPatternIds.includes(id));
			
			if (newPatternIds.length === 0) {
				return {
					errCode: 'PATTERNS_EXIST',
					errMsg: '所有图案已在播放列表中'
				}
			}
			
			// 准备新的图案对象数组
			const newPatterns = newPatternIds.map((patternId, index) => ({
				pattern_id: patternId,
				sort_order: 0, // 临时排序，稍后更新
				add_time: new Date()
			}));
			
			// 根据position参数处理插入位置
			let updatedPatterns;
			if (position === 'append') {
				// 添加到末尾
				updatedPatterns = [...playlist.patterns, ...newPatterns];
			} else {
				// 在指定位置插入
				const pos = parseInt(position, 10);
				const insertPosition = isNaN(pos) ? playlist.patterns.length : Math.min(pos, playlist.patterns.length);
				
				updatedPatterns = [...playlist.patterns];
				updatedPatterns.splice(insertPosition, 0, ...newPatterns);
			}
			
			// 更新排序
			updatedPatterns.forEach((pattern, index) => {
				pattern.sort_order = index;
			});
			
			// 更新播放列表
			await db.collection('sh_user_playlist').doc(playlistId).update({
				patterns: updatedPatterns,
				update_time: new Date()
			});
			
			return {
				errCode: 0,
				errMsg: '批量添加成功',
				data: {
					addedCount: newPatternIds.length,
					totalCount: updatedPatterns.length
				}
			}
		} catch (error) {
			console.error('批量更新播放列表图案失败:', error);
			return {
				errCode: 'UPDATE_PATTERNS_FAILED',
				errMsg: '批量更新播放列表图案失败'
			}
		}
	},
	
	/**
	 * 清空播放列表
	 * @param {string} deviceId 设备ID
	 * @param {string} userId 用户ID
	 * @returns {object} 清空结果
	 */
	async clearPlaylist({deviceId, userId}) {
		if (!deviceId || !userId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			const dbCmd = db.command;
			
			// 检查设备权限
			const deviceResult = await db.collection('sh_user_device').where(
				dbCmd.and([
					{_id: deviceId},
					dbCmd.or([
						{owner_id: userId},
						{shared_users: dbCmd.in([userId])}
					])
				])
			).get();

			if (deviceResult.data.length === 0) {
				return {
					errCode: 'NO_PERMISSION',
					errMsg: '无权限操作此设备'
				}
			}

			// 清空播放列表
			await db.collection('sh_user_playlist').where({
				device_id: deviceId
			}).update({
				patterns: [],
				current_index: 0,
				update_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '清空成功'
			}
		} catch (error) {
			console.error('清空播放列表失败:', error);
			return {
				errCode: 'CLEAR_PLAYLIST_FAILED',
				errMsg: '清空播放列表失败'
			}
		}
	}
}
